package top.wangjiu.reactive.rpc.client;

import top.wangjiu.reactive.rpc.config.ClientConfiguration;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName RpcClientContainer
 * @Description TODO
 * @Author wangjiu
 * @Date 2021/7/15 11:57 上午
 */
public class RpcClientContainer {

    private final Map<InetSocketAddress,RpcClient> clientMap = new ConcurrentHashMap<>();

    private final ClientConfiguration clientConfiguration;

    public RpcClientContainer(ClientConfiguration clientConfiguration){
        this.clientConfiguration = clientConfiguration;
    }

    public RpcClient getClient(InetSocketAddress address){
        RpcClient rpcClient = clientMap.get(address);
        if(rpcClient == null){
            synchronized (this){
                rpcClient = clientMap.get(address);
                if(rpcClient ==null){
                    rpcClient = new RpcClient(clientConfiguration,address);
                    clientMap.put(address,rpcClient);
                }
            }
        }
        return rpcClient;
    }
}
